package com.lb.baselib.http;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.bean.BaseResponse;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class SimpleLbObserver<T> implements Observer<T> {
    private static final String TAG = SimpleLbObserver.class.getName();
    private SimpleObserverOnNextListener nextListener;
    private SimpleObserverOtherListener otherListener;
//    private Context context;//有需要再加一个构造方法即可

//    public SimpleLbObserver(SimpleObserverOnNextListener listener) {
//        this.nextListener = listener;
//    }

    public SimpleLbObserver(SimpleObserverOnNextListener listener, SimpleObserverOtherListener oListener) {
        this.nextListener = listener;
        this.otherListener = oListener;
//        this.context = context;
    }

    @Override
    public void onSubscribe(Disposable d) {
        LogUtils.d(TAG, "onSubscribe: ");
        //添加业务处理
    }

    @Override
    public void onNext(T t) {
        if (t instanceof BaseResponse) {
            BaseResponse result = (BaseResponse) t;
            if (result == null) {//异常的json
                return;
            }
            if (result.getReturnCode() == ResponseCode.RESPONSE_SESSION_OUT_OF_DATE) {
                if (otherListener != null) {
                    otherListener.onSessionOutOfDate();
                }
            } else if (result.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                nextListener.onNext(t);
            } else if (result.getReturnCode() == ResponseCode.RESPONSE_ERROR) {
                if (result.getMessage() != null) {
                    otherListener.onError(result.getMessage());
                } else {
                    ToastUtils.showShort(ResponseCode.UNKNOWN_ERROR);
                }
            } else {
                ToastUtils.showShort(ResponseCode.UNKNOWN_ERROR);
            }
        }
    }

    @Override
    public void onError(Throwable error) {
        if (otherListener != null) {
            if (error.getCause() == null) {
                String msg = error.getMessage();//
                otherListener.onError(ResponseCode.UNKNOWN_ERROR);
            } else {
                String cause = error.getCause().toString();
                if (cause.contains("UnknownHostException")) {
                    if (!NetworkUtils.isConnected()) {
                        otherListener.onError("网络异常");
                    } else {
                        otherListener.onError("服务器状态异常");
                    }
                } else {
                    otherListener.onError(error.getCause().toString());
                }
            }
        }
    }

    @Override
    public void onComplete() {
        LogUtils.d(TAG, "onComplete: ");

        //添加业务处理
    }

}
